<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>鸿蒙应用调试工具-WebSocket解除-D消息发送工具</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        dark: '#1D2129',
                        light: '#F2F3F5'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-thin {
                scrollbar-width: thin;
            }
            .scrollbar-thumb-rounded {
                scrollbar-color: theme('colors.primary/30') transparent;
            }
            .scrollbar-thumb-rounded::-webkit-scrollbar {
                width: 6px;
                height: 6px;
            }
            .scrollbar-thumb-rounded::-webkit-scrollbar-thumb {
                background-color: theme('colors.primary/30');
                border-radius: 3px;
            }
            .scrollbar-thumb-rounded::-webkit-scrollbar-track {
                background: transparent;
            }
        }
    </style>
</head>
<body class="font-inter bg-gray-50 text-dark min-h-screen flex flex-col">
<!-- 顶部导航 -->
<header class="bg-white shadow-sm py-4 px-6 sticky top-0 z-10">
    <div class="container mx-auto flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-exchange text-primary text-2xl"></i>
            <h1 class="text-xl font-bold text-primary">鸿蒙应用调试工具-WebSocket解除-D消息发送工具</h1>
        </div>
        <div id="connection-status" class="flex items-center space-x-2 text-sm">
            <span class="inline-block w-2 h-2 rounded-full bg-danger"></span>
            <span>未连接</span>
        </div>
    </div>
</header>

<!-- 主内容区 -->
<main class="flex-1 container mx-auto p-4 md:p-6">
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 连接设置 -->
        <div class="lg:col-span-1 bg-white rounded-lg shadow-sm p-5">
            <h2 class="text-lg font-semibold mb-4 flex items-center">
                <i class="fa fa-connectdevelop text-primary mr-2"></i>连接设置
            </h2>
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">WebSocket 地址</label>
                    <div class="flex">
                        <input type="text" id="ws-url" value="ws://127.0.0.1:12345"
                               class="flex-1 px-3 py-2 border border-gray-300 rounded-l-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary"
                               placeholder="ws://127.0.0.1:端口">
                    </div>
                </div>
                <div class="flex gap-3">
                    <button id="connect-btn" class="flex-1 bg-primary hover:bg-primary/90 text-white py-2 px-4 rounded-md transition-colors flex items-center justify-center">
                        <i class="fa fa-plug mr-2"></i>连接
                    </button>
                    <button id="disconnect-btn" class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-700 py-2 px-4 rounded-md transition-colors flex items-center justify-center" disabled>
                        <i class="fa fa-unplug mr-2"></i>断开
                    </button>
                </div>
            </div>
        </div>

        <!-- 消息发送 -->
        <div class="lg:col-span-2 bg-white rounded-lg shadow-sm p-5">
            <h2 class="text-lg font-semibold mb-4 flex items-center">
                <i class="fa fa-paper-plane text-primary mr-2"></i>消息发送
            </h2>
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">自定义消息</label>
                    <textarea id="message-input" rows="4"
                              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary scrollbar-thin scrollbar-thumb-rounded"
                              placeholder="输入要发送的JSON格式消息..."></textarea>
                </div>
                <div class="flex flex-wrap gap-2">
                    <button class="preset-btn bg-gray-100 hover:bg-gray-200 text-gray-700 py-1 px-3 rounded-md text-sm transition-colors"
                            data-message='{"id": 1, "method": "Runtime.enable", "params": {}}'>
                        解除-D模式-命令行1
                    </button>
                    <button class="preset-btn bg-gray-100 hover:bg-gray-200 text-gray-700 py-1 px-3 rounded-md text-sm transition-colors"
                            data-message='{"id": 2, "method": "Debugger.enable", "params": { "options": ["enableLaunchAccelerate"], "maxScriptsCacheSize": 1.0E7}}'>
                        解除-D模式-命令行2
                    </button>
                    <button class="preset-btn bg-gray-100 hover:bg-gray-200 text-gray-700 py-1 px-3 rounded-md text-sm transition-colors"
                            data-message='{"id": 3, "method": "Runtime.runIfWaitingForDebugger", "params": {}}'>
                        解除-D模式-命令行3
                    </button>
                    <button class="preset-btn bg-gray-100 hover:bg-gray-200 text-gray-700 py-1 px-3 rounded-md text-sm transition-colors"
                            data-message='{"id": 1, "method": "Runtime.enable", "params": {}}&#10;{"id": 2, "method": "Debugger.enable", "params": { "options": ["enableLaunchAccelerate"], "maxScriptsCacheSize": 1.0E7}}&#10;{"id": 3, "method": "Runtime.runIfWaitingForDebugger", "params": {}}'>
                        全部解除消息
                    </button>
                </div>
                <button id="send-btn" class="w-full bg-success hover:bg-success/90 text-white py-2 px-4 rounded-md transition-colors flex items-center justify-center text-lg font-medium" disabled>
                    <i class="fa fa-paper-plane mr-2"></i>发送消息
                </button>
            </div>
        </div>

        <!-- 消息日志 -->
        <div class="lg:col-span-3 bg-white rounded-lg shadow-sm p-5">
            <h2 class="text-lg font-semibold mb-4 flex items-center">
                <i class="fa fa-history text-primary mr-2"></i>交互日志
            </h2>
            <div id="log-container" class="w-full h-80 bg-gray-50 rounded-md p-4 overflow-auto scrollbar-thin scrollbar-thumb-rounded text-sm font-mono">
                <div class="text-gray-500">=== 日志记录开始 ===</div>
            </div>
        </div>
    </div>
</main>

<!-- 页脚 -->
<footer class="bg-white py-4 px-6 border-t border-gray-200">
    <div class="container mx-auto text-center text-sm text-gray-500">
        <p>WebSocket 解除消息发送工具 &copy; 2025</p>
    </div>
</footer>

<script>
    // 全局变量
    let ws = null;
    let isConnected = false;

    // DOM 元素
    const wsUrlInput = document.getElementById('ws-url');
    const connectBtn = document.getElementById('connect-btn');
    const disconnectBtn = document.getElementById('disconnect-btn');
    const sendBtn = document.getElementById('send-btn');
    const messageInput = document.getElementById('message-input');
    const logContainer = document.getElementById('log-container');
    const connectionStatus = document.getElementById('connection-status');
    const presetBtns = document.querySelectorAll('.preset-btn');

    // 格式化时间
    function formatTime() {
        return new Date().toLocaleTimeString('zh-CN', {
            hour12: false,
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            fractionalSecondDigits: 3
        });
    }

    // 添加日志
    function addLog(message, type = 'info') {
        const logDiv = document.createElement('div');
        logDiv.className = `my-2 p-2 rounded-md ${
            type === 'send' ? 'bg-blue-50 border-l-4 border-primary' :
            type === 'receive' ? 'bg-green-50 border-l-4 border-success' :
            type === 'error' ? 'bg-red-50 border-l-4 border-danger' :
            'bg-gray-100'
        }`;

        const timeSpan = document.createElement('span');
        timeSpan.className = 'text-gray-500 mr-2';
        timeSpan.textContent = `[${formatTime()}]`;

        const contentSpan = document.createElement('span');
        contentSpan.textContent = message;

        logDiv.appendChild(timeSpan);
        logDiv.appendChild(contentSpan);

        logContainer.appendChild(logDiv);
        logContainer.scrollTop = logContainer.scrollHeight;
    }

    // 更新连接状态
    function updateConnectionStatus(connected) {
        isConnected = connected;
        const statusIcon = connectionStatus.querySelector('span:first-child');
        const statusText = connectionStatus.querySelector('span:last-child');

        if (connected) {
            statusIcon.className = 'inline-block w-2 h-2 rounded-full bg-success';
            statusText.textContent = '已连接';
            connectBtn.disabled = true;
            disconnectBtn.disabled = false;
            sendBtn.disabled = false;
            wsUrlInput.disabled = true;
            addLog('✅ 连接成功', 'info');
        } else {
            statusIcon.className = 'inline-block w-2 h-2 rounded-full bg-danger';
            statusText.textContent = '未连接';
            connectBtn.disabled = false;
            disconnectBtn.disabled = true;
            sendBtn.disabled = true;
            wsUrlInput.disabled = false;
            addLog('❌ 连接断开', 'info');
        }
    }

    // 连接 WebSocket
    connectBtn.addEventListener('click', () => {
        const url = wsUrlInput.value.trim();

        if (!url) {
            addLog('请输入WebSocket地址', 'error');
            return;
        }

        try {
            ws = new WebSocket(url);

            // 连接成功
            ws.onopen = () => {
                updateConnectionStatus(true);
            };

            // 接收消息
            ws.onmessage = (event) => {
                addLog(`📥 接收: ${event.data}`, 'receive');
            };

            // 连接关闭
            ws.onclose = (event) => {
                updateConnectionStatus(false);
                addLog(`🔌 连接关闭: ${event.code} - ${event.reason}`, 'error');
            };

            // 连接错误
            ws.onerror = (error) => {
                addLog(`❌ 连接错误: ${error.message}`, 'error');
                updateConnectionStatus(false);
            };

            addLog(`🔄 正在连接: ${url}`, 'info');
        } catch (error) {
            addLog(`❌ 连接失败: ${error.message}`, 'error');
        }
    });

    // 断开连接
    disconnectBtn.addEventListener('click', () => {
        if (ws && isConnected) {
            ws.close();
            addLog('🔌 正在断开连接...', 'info');
        }
    });

    // 发送消息
    sendBtn.addEventListener('click', () => {
        const message = messageInput.value.trim();

        if (!message) {
            addLog('请输入要发送的消息', 'error');
            return;
        }

        if (!isConnected || !ws) {
            addLog('未建立连接，请先连接服务器', 'error');
            return;
        }

        try {
            // 处理多行消息（每条消息单独发送）
            const messages = message.split('\n').filter(line => line.trim());

            messages.forEach((msg, index) => {
                // 尝试解析JSON，验证格式
                JSON.parse(msg.trim());

                ws.send(msg.trim());
                addLog(`📤 发送${messages.length > 1 ? `(${index + 1}/${messages.length})` : ''}: ${msg.trim()}`, 'send');
            });

            // 清空输入框（可选）
            // messageInput.value = '';
        } catch (error) {
            addLog(`❌ 消息格式错误: ${error.message}`, 'error');
        }
    });

    // 预设消息按钮
    presetBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const message = btn.getAttribute('data-message');
            messageInput.value = message;

            // 高亮效果
            btn.classList.add('bg-primary/10', 'text-primary');
            setTimeout(() => {
                btn.classList.remove('bg-primary/10', 'text-primary');
            }, 500);
        });
    });

    // 初始化
    addLog('✅ 工具已就绪，可以开始连接', 'info');
</script>
</body>
</html>